package com.lanyou.cook.camel.service;

import java.util.List;

import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.log4j.Logger;

import com.lanyou.cook.camel.util.CamelFactory;

/**
 * leader的监听实现类，在监听到获取leader后，调用camel-ftp接口服务，并将应用标记成为leader，只要leader才能运行camel-ftp
 * @author ly-lihailang
 *
 */
public class LoadCamelFtpService implements LeaderLatchListener{
	private static Logger logger = Logger.getLogger(LoadCamelFtpService.class);
	private LeaderElectionService leaderElectionService;
	private CamelService camelService;
	private final Object schedulerLock = new Object();
	
	/**
	 * 初始化启动camel-ftp
	 */
	public void init(){
		logger.info("[LoadCamelFtpService.init]:------------");
		runCamelFtpSchedule();
	}
	/**
	 * 实例销毁时调用，将该监听移除，并将本机已启动的camel-ftp接口服务停止
	 */
	public void close(){
		logger.info("[LoadCamelFtpService.close]:-----------------------");
		leaderElectionService.removeListener(this);
		notLeader();
	}
	/**
	 * 该方法是监听获取 Leader时调用
	 */
	@Override
	public void isLeader() {
		logger.info("[LoadCamelFtpService.isLeader]:本机执行");
		//设置本机为Leader
		CamelFactory.isLeader=true;
		synchronized (schedulerLock) {
			//启动camel-ftp接口
			List<String> codeList = camelService.getAllFtpCode();
			if(codeList.size()>0){
				for(String code:codeList){
					camelService.restartCamel(code);
				}
			}else{
				logger.info("[LoadCamelFtpService.isLeader]:没有可执行的任务");
			}
		}
		
	}

	/**
	 * 监听LeaderLatch不再是leader了就调用该方法
	 */
	@Override
	public void notLeader() {
		//当该机不再是leader时调用
		synchronized (schedulerLock) {
			logger.info("[LoadCamelFtpService.notLeader]:------------------");
			CamelFactory.isLeader=false;
			camelService.close();
		}
	}
	
	/**
	 * 运行camel-ftp
	 */
	public void runCamelFtpSchedule(){
		//判断LeaderLatch是否为Leader，如果是，则启动
		if(leaderElectionService.isLeader()){
			isLeader();
		}
		//将本监听添加到LeaderLatch，监听LeaderLatch
		leaderElectionService.addListener(this);
	}

	public LeaderElectionService getLeaderElectionService() {
		return leaderElectionService;
	}

	public void setLeaderElectionService(LeaderElectionService leaderElectionService) {
		this.leaderElectionService = leaderElectionService;
	}
	public CamelService getCamelService() {
		return camelService;
	}
	public void setCamelService(CamelService camelService) {
		this.camelService = camelService;
	}
}
